<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { getUserCarsApi, addUserCarApi, updateUserCarApi, deleteUserCarApi } from '@/api/car';

// 车辆列表数据
const cars = ref([]);
// 对话框状态
const dialogVisible = ref(false);
// 对话框类型
const dialogType = ref('add');
// 表单引用
const carFormRef = ref();

// 车辆表单数据
const carForm = ref({
  id: '',
  brand: '',
  model: '',
  plateNumber: '',
  year: '',
  mileage: '', // 后端Car实体类中是String类型
  color: ''
});

// 表单验证规则
const rules = {
  brand: [
    { required: true, message: '请输入汽车品牌', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入汽车型号', trigger: 'blur' }
  ],
  plateNumber: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  year: [
    { required: true, message: '请选择购买年份', trigger: 'change' }
  ],
  mileage: [
    { required: true, message: '请输入行驶里程', trigger: 'blur' },
  ],
  color: [
    { required: true, message: '请输入车辆颜色', trigger: 'blur' }
  ]
};

// 获取用户车辆列表
const getCars = async () => {
  //加载localStorage存储的员工登录信息
  
    const loginUserStr = localStorage.getItem('loginUser');
    if (!loginUserStr) {
      ElMessage.error('请先登录');
      return;
    }
    
    const loginUser = JSON.parse(loginUserStr);
    const result = await getUserCarsApi(loginUser.id);
    if (result.code === 1) { 
      cars.value = result.data;
    } else {
      ElMessage.error(result.msg || '获取车辆列表失败');
    }
  } 


// 重置表单
const resetForm = () => {
  if (carFormRef.value) {
    carFormRef.value.resetFields();
  }
  carForm.value = {
    id: '',
    brand: '',
    model: '',
    plateNumber: '',
    year: '',
    mileage: '',
    color: ''
  };
};

// 打开添加车辆对话框
const openAddCarDialog = () => {
  dialogType.value = 'add';
  resetForm();
  dialogVisible.value = true;
};

// 打开编辑车辆对话框
const openEditCarDialog = (car) => {
  dialogType.value = 'edit';
  carForm.value = {
    ...car,
  };
  dialogVisible.value = true;
};

// 添加车辆
const addCar = async () => {
  try {
    const loginUserStr = localStorage.getItem('loginUser');
    const loginUser = JSON.parse(loginUserStr);
    const carData = {
      ...carForm.value,
      userId: loginUser.id
    };
    
    const result = await addUserCarApi(carData);
    
    if (result.code === 1) {
      ElMessage.success('车辆添加成功');
      dialogVisible.value = false;
      getCars();
    } else {
      ElMessage.error(result.msg || '添加车辆失败');
    }
  } catch (error) {
    console.error('添加车辆失败:', error);
    ElMessage.error('添加车辆失败，请稍后重试');
  }
};

// 更新车辆
const updateCar = async () => {
  try {
    const loginUserStr = localStorage.getItem('loginUser');
    const loginUser = JSON.parse(loginUserStr);
    const carData = {
      ...carForm.value,
      userId: loginUser.id
    };
    
    const result = await updateUserCarApi(carData);
    
    if (result.code) {
      ElMessage.success('车辆信息更新成功');
      dialogVisible.value = false;
      getCars();
    } else {
      ElMessage.error(result.msg || '更新车辆失败');
    }
  } catch (error) {
    console.error('更新车辆失败:', error);
    ElMessage.error('更新车辆失败，请稍后重试');
  } finally {
    loading.close();
  }
};

// 提交表单
const handleSubmit = async () => {
  try {
    await carFormRef.value.validate();
    if (dialogType.value === 'add') {
      await addCar();
    } else {
      await updateCar();
    }
  } catch (error) {
    // 表单验证失败时会抛出错误，这里不做处理
  }
};

// 删除车辆
const deleteCar = async (carId) => {
  try {
    const result = await deleteUserCarApi(carId);
    
    if (result.code === 1) {
      ElMessage.success('车辆删除成功');
      getCars();
    } else {
      ElMessage.error(result.msg || '删除车辆失败');
    }
  } catch (error) {
    console.error('删除车辆失败:', error);
    ElMessage.error('删除车辆失败，请稍后重试');
  }
};

// 确认删除车辆
const confirmDeleteCar = (carId) => {
  ElMessageBox.confirm('确定要删除这辆车吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteCar(carId);
  }).catch(() => {
    // 取消删除
  });
};

// 页面加载时获取车辆列表
onMounted(() => {
  getCars();
});
</script>

<template>
  <div class="my-cars-container">
    <h2>我的车辆</h2>
    <div class="header-actions">
      <el-button type="primary" @click="openAddCarDialog">
        <el-icon><Plus /></el-icon> 添加车辆
      </el-button>
      <el-button @click="getCars">
        刷新车辆列表
      </el-button>
      <span class="car-count">车辆数量: {{ cars.length }}</span>
    </div>

    
    <!-- 车辆列表 -->
    <div class="car-list">
      <div v-if="cars.length === 0" class="empty-state">
        <el-empty description="暂无车辆信息" />
      </div>
      
      <el-row :gutter="20" v-else>
        <el-col :span="8" v-for="car in cars" :key="car.id">
          <el-card class="car-card" :body-style="{ padding: '20px' }">
            <div class="car-info">
              <div class="car-name">{{ car.brand }} {{ car.model }}</div>
              <div class="car-details">
                <div class="detail-item">
                  <span class="label">车牌号：</span>
                  <span class="value">{{ car.plateNumber }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">年份：</span>
                  <span class="value">{{ car.year }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">行驶里程：</span>
                  <span class="value">{{ car.mileage }}km</span>
                </div>
                <div class="detail-item">
                  <span class="label">车辆颜色：</span>
                  <span class="value">{{ car.color }}</span>
                </div>
              </div>
              
              <div class="car-actions">
                <el-button type="primary" size="small" @click="openEditCarDialog(car)">
                  <el-icon><Edit /></el-icon> 编辑
                </el-button>
                <el-button type="danger" size="small" @click="confirmDeleteCar(car.id)">
                  <el-icon><Delete /></el-icon> 删除
                </el-button>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    
    <!-- 添加/编辑车辆对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加车辆' : '编辑车辆'"
      width="500px"
    >
      <el-form :model="carForm" :rules="rules" ref="carFormRef" label-width="100px">
        <el-form-item label="汽车品牌" prop="brand">
          <el-input v-model="carForm.brand" placeholder="请输入汽车品牌" />
        </el-form-item>
        <el-form-item label="汽车型号" prop="model">
          <el-input v-model="carForm.model" placeholder="请输入汽车型号" />
        </el-form-item>
        <el-form-item label="车牌号" prop="plateNumber">
          <el-input v-model="carForm.plateNumber" placeholder="请输入车牌号" />
        </el-form-item>
        <el-form-item label="购买年份" prop="year">
          <el-input v-model="carForm.year" placeholder="请输入购买年份" />
        </el-form-item>
        <el-form-item label="行驶里程" prop="mileage" style="align-items: center;">
        <div style="display: flex; align-items: center; flex: 1;">
          <!-- 输入框去掉右侧内边距，单位去掉左侧间距，实现无缝贴合 -->
          <el-input 
            v-model="carForm.mileage" 
            placeholder="请输入行驶里程" 
            style="margin-right: 0; padding-right: 5px;"
          />
          <span style="margin-left: 0; padding-left: 5px;">km</span>
        </div>
      </el-form-item>
        <el-form-item label="车辆颜色" prop="color">
          <el-input v-model="carForm.color" placeholder="请输入车辆颜色" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.my-cars-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.my-cars-container h2 {
  margin-bottom: 20px;
  color: #303133;
}

.header-actions {
  margin-bottom: 20px;
}

.header-actions .el-button {
  margin-right: 10px;
}

.car-count {
  color: #606266;
  margin-left: 10px;
}

.car-list {
  margin-top: 20px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.car-card {
  height: 100%;
  transition: all 0.3s ease;
  margin-bottom: 20px;
}

.car-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.car-info {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.car-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #303133;
}

.car-details {
  flex: 1;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.label {
  color: #606266;
}

.value {
  color: #303133;
  font-weight: 500;
}

.car-actions .el-button {
  margin-right: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>